<?php
namespace app\wap\controller;
use app\common\model\AutoreplyModel;
class Api
{
    public $wx_config=[];
    public function __construct(){
        $config = cache('db_config_data');

        if(!$config){
            $config = api('Config/lists');
            cache('db_config_data',$config);
        }
        config($config);
        $this->wx_config= [
            'token'             => config('wx_token'), // 填写你设定的key
            'appid'             => config('wx_appid'), // 填写高级调用功能的app id, 请在微信开发模式后台查询
            'appsecret'         => config('wx_appsecret'), // 填写高级调用功能的密钥
            'encodingaeskey'    => config('wx_encodingaeskey'), // 填写加密用的EncodingAESKey（可选，接口传输选择加密时必需）
            'mch_id'            => config('wx_mch_id'), // 微信支付，商户ID（可选）
            'partnerkey'        => config('wx_partnerkey'), // 微信支付，密钥（可选）
            'ssl_cer'           =>  config('wx_ssl_cer'), // 微信支付，证书cert的路径（可选，操作退款或打款时必需）
            'ssl_key'           =>  config('wx_ssl_key'), // 微信支付，证书key的路径（可选，操作退款或打款时必需）
            //    'cachepath'         => config('wx_appid'), // 设置SDK缓存目录（可选，默认位置在./src/Cache下，请保证写权限）
        ];
    }
    public function index()
    {

        $Receive=new \Wechat\WechatReceive($this->wx_config);

        $Receive->valid();

        $type = $Receive->getRev()->getRevType();

        $postStr = file_get_contents("php://input");
      //  file_put_contents(RUNTIME_PATH.'aa.txt',var_export($postStr,true));
        switch($type) {
            case $Receive::MSGTYPE_TEXT:

                //把消息传给 类
                $WordProcess=new  \Wechat\WordProcess();
                //获取类的 要返回类型
                //这里返回
                if($WordProcess->process($Receive->getRevContent())){
                    $Receive->text($WordProcess->parameter)->reply();
                }else{
                    $Receive->text(config('wx_default_reply'))->reply();
                }


                break;
            case $Receive::MSGTYPE_EVENT:
                $event=$Receive->getRevEvent();

                if($event['event'] == 'CLICK' ){
                    //把消息传给 类
                    $WordProcess=new  \Wechat\WordProcess();
                    //获取类的 要返回类型
                    //这里返回
                    if($WordProcess->process($event['key'])){
                        $Receive->text($WordProcess->parameter)->reply();
                    }else{
                        $Receive->text(config('wx_default_reply'))->reply();
                    }

                }elseif($event['event'] == 'subscribe'){
                    //关注
                    $FromUserName=$Receive->getRevFrom();
                    //查看是否关注过
                    $ret = db('oauth_member')->field('id,mid')->where(['openid'=>$FromUserName])->find();
                    //无论有没有关注过 都获取下信息 在更新一次
                    $WechatUser =  new \Wechat\WechatUser($this->wx_config);
                    $userinfo = $WechatUser->getUserInfo($FromUserName);
                    $userinfo['nickname'] = preg_replace('~\xEE[\x80-\xBF][\x80-\xBF]|\xEF[\x81-\x83][\x80-\xBF]~', '', $userinfo['nickname']);

                    if($ret){
                        //说明关注过了
                        if($ret['mid']>0){
                            $user=db('member')->find($ret['mid']);
                            //存在了就在更新下用户信息表
                            db('member')->where(['id'=>$ret['mid']])->update([
                                'nickname'=>$userinfo['nickname'],
                                'sex'=>$userinfo['sex'],
                                'group_id'=>'1',
                                'head_img'=>$userinfo['headimgurl'],
                                'update_time'=>time()
                            ]);

                        }else{
                            //不存在了 直接创建关联
                            $mid=db('member')->insert([
                                'nickname'=>$userinfo['nickname'],
                                'sex'=>$userinfo['sex'],
                                'group_id'=>'1',
                                'head_img'=>$userinfo['headimgurl'],
                                'create_time'=>time(),
                                'update_time'=>time(),
                                'login_num'=>1,
                                'status'=>1
                            ],false,true);
                            //在更新微信表的MID
                            db('oauth_member')->where(['id'=>$ret['id']])->update(['mid'=>$mid]);
                        }

                    }else{
                        //先插入到微信表内
                        $wid=db('oauth_member')->insert(
                            [
                                'type'=>1,
                                'openid'=>$userinfo['openid'],
                                'nickname'=>$userinfo['nickname'],
                                'sex'=>$userinfo['sex'],
                                'city'=>$userinfo['city'],
                                'province'=>$userinfo['province'],
                                'headimgurl'=>$userinfo['headimgurl'],
                                'create_time'=>time(),
                                'update_time'=>time()
                            ],false,true
                        );
                        //在插入到 member表内
                        if($wid){
                            $mid=db('member')->insert([
                                'nickname'=>$userinfo['nickname'],
                                'sex'=>$userinfo['sex'],
                                'group_id'=>'1',
                                'head_img'=>$userinfo['headimgurl'],
                                'create_time'=>time(),
                                'update_time'=>time(),
                                'login_num'=>1,
                                'status'=>1
                            ],false,true);
                            //在更新微信表的MID
                            db('oauth_member')->where(['id'=>$wid])->update(['mid'=>$mid]);
                        }

                    }
                    // 关注时回复信息
                    $Receive->text(config('wx_focus'))->reply();
                    exit;
                }elseif($event['event'] == 'unsubscribe'){
                    //取消关注
                }elseif($event['event'] == 'LOCATION'){
                    $geo = $Receive->getRevEventGeo();
                    //file_put_contents(RUNTIME_PATH.'gg.txt',var_export($geo,true));
                }elseif($event['event'] == 'SCAN'){
                    //判断是否失效


                    //file_put_contents(RUNTIME_PATH.'gg.txt',var_export($geo,true));
                }
                break;
            case $Receive::MSGTYPE_IMAGE:
                break;
            default:
                $Receive->text(config('wx_default_reply'))->reply();
        }

    }
    private function subscribe(){

    }

    private function autoreply($text){
        $result=db('weixin_autoreply')->where(['status'=>1])->order('id asc')->select();
    }
    public function getJsSign($u){
        $WechatScript=new \Wechat\WechatScript($this->wx_config);
         return  $WechatScript->getJsSign($u);
    }
}
